package com.kld.web.controller.common;

import com.kld.common.constant.Constants;
import com.kld.common.utils.UUIDUtil;
import com.kld.framework.config.RuoYiConfig;
import org.jodconverter.JodConverter;
import org.jodconverter.office.LocalOfficeManager;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;
import org.jodconverter.office.OfficeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileViewController {

    @Value("${kld.openOffice}")
    private String openOffice;

    @Autowired
    public RedisTemplate redisTemplate;

    Map<String, String> fileMap = new HashMap<String, String>();


    @GetMapping("/demoHtml")
    public String demoHtml(Model model) {
        return "index";
    }

    /**
     * 文件预览，通过fileId从文件服务器获取文件，并以流的方式响应
     *
     * @param fileName
     * @param response
     */
    @RequestMapping("/resource/downloadLocal/{fileName}")
    public void downloadLocal(@PathVariable String fileName, HttpServletResponse response) throws IOException {

        String target = "/TEMP_FILE/" + fileName + ".pdf";
        String path = RuoYiConfig.getProfile() + target;
        // 读到流中
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        // 从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }

    @GetMapping("/resource/view")
    public String fileview(String file, String url,Model model) {
        if (StringUtils.hasLength(file)) {
            if (file.endsWith(".pdf") || file.endsWith(".jpg")) {
                model.addAttribute("file", url+Constants.RESOURCE_PREFIX+file);
                model.addAttribute("url", url);
            } else if (file.endsWith(".docx") || file.endsWith(".doc") || file.endsWith(".xlsx") || file.endsWith(".xls") || file.endsWith("pptx")) {
                // 执行转换
                String uuid = UUIDUtil.getUUID();
                String target = RuoYiConfig.getProfile() + "/TEMP_FILE/" + uuid + ".pdf";
                OfficeManager officeManager = null;
                try {
                    File sourceFile = new File(RuoYiConfig.getProfile() + file);
                    Map<String,String> resourceMap= redisTemplate.opsForHash().entries("resourceMap");
                    if (!resourceMap.containsKey(sourceFile.getPath())) {
                        officeManager = LocalOfficeManager.builder().install()
                                .officeHome(openOffice).build();
                        officeManager.start();
                        File targetFile = new File(target);
                        JodConverter.convert(sourceFile).to(targetFile).execute();
                        fileMap.put(sourceFile.getPath(), uuid);
                        redisTemplate.opsForHash().putAll("resourceMap",fileMap);
                        model.addAttribute("file", url+"/resource/downloadLocal/" + uuid);
                        model.addAttribute("url", url);
                    } else {
                        model.addAttribute("file", url+"/resource/downloadLocal/" + resourceMap.get(sourceFile.getPath()));
                        model.addAttribute("url", url);
                    }

                    return "iframe";
                } catch (OfficeException e) {
                    e.printStackTrace();
                } finally {
                    OfficeUtils.stopQuietly(officeManager);
                }
            }
        }
        return "iframe";
    }
}
